<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 任务名称输入框 -->
      <el-form-item label="任务名称" prop="nodeName">
        <el-input v-model="queryParams.nodeName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 搜索和重置按钮 -->
      <el-form-item>
        <el-button type="primary" icon="Search" size="default" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 流程实例表格 -->
    <el-table :data="instanceList">
      <!-- 表格列定义 -->
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center" key="id" prop="id">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程实例id" align="center" prop="instanceId" :show-overflow-tooltip="true" />
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="任务名称" align="center" prop="nodeName" :show-overflow-tooltip="true" />
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true" />
      <el-table-column label="协作类型" align="center" prop="cooperateType" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="cooperateType" :value="scope.row.cooperateType" />
        </template>
      </el-table-column>
      <el-table-column label="协作人" align="center" prop="collaborator" :show-overflow-tooltip="true" />
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="flow_status" :value="scope.row.flowStatus" />
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="110" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" type="primary" link
            @click="showDoneList(scope.row.instanceId, scope.row.formPath, scope.row.infoVo, scope.row)"
            v-hasPermi="['flow:execute:doneList']">审批记录</el-button>
          <el-button size="small" type="primary" link @click="toFlowImage(scope.row.instanceId)">流程图</el-button>
          <el-button size="small" type="primary" link v-if="scope.row.ext" @click="handle(scope.row)">查看</el-button>
          <el-button size="small" type="primary" link @click="handleComponent">多组件加载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="流程图" width="70%" v-model="flowChart" append-to-body>
      <WarmChart :insId="insId"></WarmChart>
    </el-dialog>

    <component v-if="approve" :is="approve" :businessId="businessId" :taskId="taskId" :infoVo="infoVo"
      @refresh="getList"></component>
    <!-- 动态加载的组件 -->
    <el-dialog title="审批详情" v-model="approveDialogVisible" width="80%">
      <component :is="dynamicComponent" v-if="dynamicComponent" :infoVo="infoVo" :taskId="taskId" :disabled="false" />
    </el-dialog>
    <!-- 多组件加载 -->
    <el-dialog title="多组件加载" v-model="componentVisible" width="80%">
      <component v-for="(item, index) in componentList" :key="index" :is="item.approve"></component>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    onMounted,
    defineAsyncComponent,
    getCurrentInstance
  } from 'vue'
  import {
    donePage
  } from "@/api/flow/execute";
  import WarmChart from "@/views/flow/definition/warm_chart.vue";
  import {
    parseTime
  } from '@/utils/ruoyi'
  import {
    useRouter
  } from 'vue-router'
  import {
    useDict
  } from '@/utils/dict'
  // 路由实例
  const router = useRouter()

  // 响应式变量
  const ids = ref([])
  const showSearch = ref(true)
  const flowChart = ref(false)
  const insId = ref(null)
  const total = ref(0)
  const businessId = ref(null)
  const instanceList = ref([])
  const approve = ref(null)
  const dynamicComponent = ref(null)
  const approveDialogVisible = ref(false)
  const infoVo = ref(null)
  const taskId = ref(null)
  const componentVisible = ref(false)
  const componentList = ref([])
  const formPath = ref('')

  // 查询参数
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    nodeName: null,
    flowStatus: null,
    createTime: null,
    businessId: null
  })
  const cooperateType = ref([{
      label: '审批',
      value: '1'
    },
    {
      label: '转办',
      value: '2'
    },
    {
      label: '委派',
      value: '3'
    },
    {
      label: '会签',
      value: '4'
    },
    {
      label: '票签',
      value: '5'
    },
    {
      label: '加签',
      value: '6'
    },
    {
      label: '减签',
      value: '7'
    }
  ]);
  const {
    flow_status
  } = useDict('flow_status');
  // 生命周期：组件挂载时
  onMounted(() => {
    getList()
  })

  /** 查询流程实例列表 */
  const getList = () => {
    donePage(queryParams.value).then(response => {
      console.log('接口返回数据：', response);
      instanceList.value = response.rows;
      total.value = Number(response.total);
    });
  };

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1
    console.log('查询参数', queryParams.value)
    getList()
  }
  // 获取表单实例并重置
  const {
    proxy
  } = getCurrentInstance()
  /** 重置按钮操作 */
  const resetQuery = () => {
    proxy.$refs.queryForm.resetFields()
    handleQuery()
  }

  /** 查看审批记录 */
  const showDoneList = (instanceId, formPath, infoVo, row) => {
    const params = {
      disabled: false,
      pageNum: queryParams.value.pageNum,
      formPath,
      infoVo,
      businessId: row.businessId || queryParams.value.businessId
    }
    router.push({
      path: `/done/doneList/index/${instanceId}`,
      query: params
    })
  }

  /** 查看流程图 */
  const toFlowImage = (instanceId) => {
    insId.value = instanceId
    flowChart.value = true
  }

  /** 查看详情 */
  const handle = (row) => {
    // 设置任务ID和业务ID
    taskId.value = row.id
    businessId.value = row.businessId

    // 解析ext字段的JSON数据
    if (row.ext) {
      try {
        const parsedExt = JSON.parse(row.ext)
        infoVo.value = {
          ...parsedExt
        }
      } catch (e) {
        console.error('Invalid ext JSON format:', row.ext)
      }
    }
    // 获取或设置formPath路径
    const currentFormPath = row.formPath || formPath.value
    approve.value = defineAsyncComponent(() => import('@/views/system/leave/see.vue'));
    // 动态加载组件
    // if (currentFormPath) {
    //   approve.value = defineAsyncComponent(() => import(`@/views/${currentFormPath}`))
    // } else {
    //   approve.value = null
    // }
  }

  /** 加载多组件 */
  const handleComponent = () => {
    componentList.value.push({
      approve: defineAsyncComponent(() => import(`@/views/system/role`))
    })
    componentList.value.push({
      approve: defineAsyncComponent(() => import(`@/views/system/user`))
    })
    componentVisible.value = true
  }
</script>